/** 现货市场  伏羲储能 */
import { yunNao } from "@src/api/yunNao"
import { SMPrivateCodeConfig, SMPrivateCodes, arrHasVal, getPrivateCommonParams } from "./data"
import { requestSDspotMarket } from "@src/api/fetch"
import { getDdifferenceDate } from "@src/utils/common"
import { spotMarketCommon } from "@src/api/spotMarket"
import dayjs from "dayjs"

 /** V2
   * 【现货市场】-【现货交易】-【实时交易结果】-【实时交易结果查询（临时）】
   * 节点电价（实时-临时）
   * REALTIME_NODE_PRICE_INFO = "realtime_node_price_info",
   */
//  export const saveFengZe = async (data:any, dataDate:string) => {
//   try {
//    const nodePrice = (data?.data || []).map((val:any) => val?.cqPrice)
//    const saveParams = {
//       sourceId: 1,
//       "itemCode": SMPrivateCodes.NODE_ELECTRICITY_PRICE_TEMPORARY,
//       source: '山东交易中心',
//       dataDate,
//       data:[{
//        nodeId: getAccountNodeInfo().nodeId,
//        nodePrice
//       }]
//     }
//     console.log('存储数据：', saveParams)
//     if(arrHasVal(nodePrice)) {
//       await yunNao.saveJson(saveParams)
//       console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
//     }else {
//       console.log('无数据 不存')
//     }
//   }catch(e) {
//     console.error(e)
//   }
// }

const getSavePrivateDayOutputQuan = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【现货市场】-【现货交易】-【日前交易结果】-【一次日前交易结果查询（新版）】- 出力 电量')
  console.log('getSavePrivateDayOutputQuan', {headers, unitid})
  try {
    const { dataDate = ''} = SMPrivateCodeConfig[SMPrivateCodes.DAY_TRADING_RESULT_OUTPUT] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/DaJyjgfbPlantFirQuery24.do?method=getDetail&unitid=${unitid}&draw=1`,
      { },
      { method:'get', headers }
    )

    const outputList = dataObj?.data?.map?.((val:any) => val?.power || null) || []
    const quanList = dataObj?.data?.map?.((val:any) => val?.energy || null) || []
  
    const saveOutputParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.DAY_TRADING_RESULT_OUTPUT,
     dataDate: pdate,
     output: outputList
    }
    const saveQuanParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.DAY_TRADING_RESULT_QUAN,
     dataDate: pdate,
     quan: quanList
    }
    
    console.log('存储数据：day getSavePrivateDayOutputQuan', saveOutputParams)
    console.log('存储数据：day getSavePrivateDayOutputQuan', saveQuanParams)
    if(arrHasVal(outputList) || arrHasVal(quanList)) {
      if(arrHasVal(outputList)) await yunNao.saveJson(saveOutputParams)
      if(arrHasVal(quanList)) await yunNao.saveJson(saveQuanParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【现货市场】-【现货交易】-【日前交易结果】-【一次日前交易结果查询（新版）】 出清电价
const getSavePrivateDayPrice = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【现货市场】-【现货交易】-【日前交易结果】-【一次日前交易结果查询（新版）】- 出清电价')
  console.log('getSavePrivateDayPrice', {headers, unitid})
  try {
    const { dataDate = '', realUnitId = unitid} = SMPrivateCodeConfig[SMPrivateCodes.DAY_TRADING_RESULT_PRICE] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/DaJyjgfbPlantFirQuery24.do?method=getDetail&unitid=${realUnitId}&draw=1`,
      { },
      { method:'get', headers }
    )

    const priceList = dataObj?.data?.map?.((val:any) => val?.cqPrice || null) || []
  
    const saveDayPriceParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.DAY_TRADING_RESULT_PRICE,
     dataDate: pdate,
     price: priceList
    }
    
    console.log('存储数据：day getSavePrivateDayPrice', saveDayPriceParams)
    if(arrHasVal(saveDayPriceParams.price)) {
      await yunNao.saveJson(saveDayPriceParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【现货市场】-【现货交易】-【日前交易结果】-【日前交易结果查询】(二次)- 出力 电量'
const getSavePrivateDayTwoOutputQuan = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【现货市场】-【现货交易】-【日前交易结果】-【日前交易结果查询】(二次)- 出力 电量')
  console.log('getSavePrivateDayTwoOutputQuan', {headers, unitid})
  try {
    const { dataDate = ''} = SMPrivateCodeConfig[SMPrivateCodes.DAY_TWO_TRADING_RESULT_OUTPUT] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/DaJyjgfbPlantQuery24.do?method=getDetail&unitid=${unitid}&draw=1`,
      { },
      { method:'get', headers }
    )

    const outputList = dataObj?.data?.map?.((val:any) => val?.power || null) || []
    const quanList = dataObj?.data?.map?.((val:any) => val?.energy || null) || []
  
    const saveOutputParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.DAY_TWO_TRADING_RESULT_OUTPUT,
     dataDate: pdate,
     output: outputList
    }
    const saveQuanParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.DAY_TWO_TRADING_RESULT_QUAN,
     dataDate: pdate,
     quan: quanList
    }
    
    console.log('存储数据：day getSavePrivateDayTwoOutputQuan', saveOutputParams)
    console.log('存储数据：day getSavePrivateDayTwoOutputQuan', saveQuanParams)
    if(arrHasVal(outputList) || arrHasVal(quanList)) {
      if(arrHasVal(outputList)) await yunNao.saveJson(saveOutputParams)
      if(arrHasVal(quanList)) await yunNao.saveJson(saveQuanParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【现货市场】-【现货交易】-【日前交易结果】-【日前交易结果查询】(二次) 出清电价
const getSavePrivateDayTwoPrice = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【现货市场】-【现货交易】-【日前交易结果】-【日前交易结果查询】(二次)- 出清电价')
  console.log('getSavePrivateDayTwoPrice', {headers, unitid})
  try {
    const { dataDate = '', realUnitId = unitid} = SMPrivateCodeConfig[SMPrivateCodes.DAY_TWO_TRADING_RESULT_PRICE] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/DaJyjgfbPlantQuery24.do?method=getDetail&unitid=${realUnitId}&draw=1`,
      { },
      { method:'get', headers }
    )

    const priceList = dataObj?.data?.map?.((val:any) => val?.cqPrice || null) || []
  
    const saveDayPriceParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.DAY_TWO_TRADING_RESULT_PRICE,
     dataDate: pdate,
     price: priceList
    }
    
    console.log('存储数据：day getSavePrivateDayTwoPrice', saveDayPriceParams)
    if(arrHasVal(saveDayPriceParams.price)) {
      await yunNao.saveJson(saveDayPriceParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【现货市场】-【现货交易】-【实时交易结果】-【实时交易结果查询（正式数据）】 出力 电量
const getSavePrivaterRealtimeOutputQuan = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【现货市场】-【现货交易】-【实时交易结果】-【实时交易结果查询（正式数据）】- 出力 电量')
  console.log('getSavePrivaterRealtimeOutputQuan', {headers, unitid})
  try {
    const { dataDate = ''} = SMPrivateCodeConfig[SMPrivateCodes.REALTIME_TRADING_RESULT_OUTPUT] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/YxJyjgfbPlantQuery24.do?method=getDetail&unitid=${unitid}&draw=1`,
      { },
      { method:'get', headers }
    )

    const outputList = dataObj?.data?.map?.((val:any) => val?.power || null) || []
    const quanList = dataObj?.data?.map?.((val:any) => val?.energy || null) || []
  
    const saveOutputParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.REALTIME_TRADING_RESULT_OUTPUT,
     dataDate: pdate,
     output: outputList
    }
    const saveQuanParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.REALTIME_TRADING_RESULT_QUAN,
     dataDate: pdate,
     quan: quanList
    }
    
    console.log('存储数据：realtime getSavePrivaterRealtimeOutputQuan', saveOutputParams)
    console.log('存储数据：realtime getSavePrivaterRealtimeOutputQuan', saveQuanParams)
    if(arrHasVal(saveOutputParams.output) || arrHasVal(saveQuanParams.quan)) {
      if(arrHasVal(saveOutputParams.output)) await yunNao.saveJson(saveOutputParams)
      if(arrHasVal(saveQuanParams.quan)) await yunNao.saveJson(saveQuanParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【现货市场】-【现货交易】-【实时交易结果】-【实时交易结果查询（正式数据）】 出清电价
const getSavePrivaterRealtimePrice = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【现货市场】-【现货交易】-【实时交易结果】-【实时交易结果查询（正式数据）】- 出清电价')
  console.log('getSavePrivaterRealtimePrice', {headers, unitid})
  try {
    const { dataDate = '', realUnitId = unitid} = SMPrivateCodeConfig[SMPrivateCodes.REALTIME_TRADING_RESULT_PRICE] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/YxJyjgfbPlantQuery24.do?method=getDetail&unitid=${realUnitId}&draw=1`,
      { },
      { method:'get', headers }
    )

    const priceList = dataObj?.data?.map?.((val:any) => val?.cqPrice || null) || []
  
    const saveRealtimePriceParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.REALTIME_TRADING_RESULT_PRICE,
     dataDate: pdate,
     price: priceList
    }
    
    console.log('存储数据：realtime getSavePrivaterRealtimePrice', saveRealtimePriceParams)
    if(arrHasVal(saveRealtimePriceParams.price)) {
      await yunNao.saveJson(saveRealtimePriceParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【日前交易申报】-【电能量申报查询】
const getSaveTradeReportQuatation = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【日前交易申报】-【电能量申报查询】')
  console.log('getSaveTradeReportQuatation', {headers, unitid})
  try {
    const { dataDate = '', realUnitId = unitid} = SMPrivateCodeConfig[SMPrivateCodes.QUOTATION_CURVE] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const params = new FormData()
    params.append('pdate', pdate)
    params.append('unitid', realUnitId || '')

    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/DaJysbPlantQuery.do?method=getDlDataCn`,
      params,
      { method:'post', headers: {...headers, 
        // 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
      } }
    )

    const quotationList = dataObj?.data || []
  
    const saveQuotationParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.QUOTATION_CURVE,
     dataDate: pdate,
     quotation: quotationList
    }
    
    console.log('存储数据：getSaveTradeReportQuatation', saveQuotationParams)
    if(arrHasVal(saveQuotationParams.quotation)) {
      await yunNao.saveJson(saveQuotationParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

// 【日前交易申报】-【电能量申报查询】- 运行参数
const getSaveTradeReportOperatingParameter = async ({headers, unitid, certainDate}:{headers:HeadersInit, unitid?:string, certainDate?:string}) => {
  console.log('【日前交易申报】-【电能量申报查询】- 运行参数')
  console.log('getSaveTradeReportOperatingParameter', {headers, unitid})
  try {
    const { dataDate = '', realUnitId = unitid} = SMPrivateCodeConfig[SMPrivateCodes.QUOTATION_OPERATING_PARAMETER] || {}
  
    const pdate = certainDate ? certainDate : getDdifferenceDate(dataDate as number)
  
    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(pdate)
  
    const params = new FormData()
    params.append('pdate', pdate)
    params.append('unitid', realUnitId || '')

    const dataObj = await requestSDspotMarket(
      `https://pmos.sd.sgcc.com.cn:18080/trade/DaJysbPlantQuery.do?method=getYxcsData`,
      params,
      { method:'post', headers: {...headers, 
        // 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
      } }
    )
  
    const saveQuotationParams = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: SMPrivateCodes.QUOTATION_OPERATING_PARAMETER,
     dataDate: pdate,
     operatingParameter: dataObj || {}
    }
    
    console.log('存储数据：getSaveTradeReportOperatingParameter', saveQuotationParams)
    if(Object.keys(saveQuotationParams.operatingParameter).length) {
      await yunNao.saveJson(saveQuotationParams)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }else {
      console.log('无数据 不存')
    }
  } catch(e) {
    console.error(e)
  }
}

/** 伏羲储能 私有数据方法 */
export const getFuXiChuNengFnList = () => ([
  getSavePrivateDayOutputQuan,
  getSavePrivateDayPrice,
  getSavePrivateDayTwoOutputQuan,
  getSavePrivateDayTwoPrice,
  getSavePrivaterRealtimeOutputQuan,
  getSavePrivaterRealtimePrice,
  getSaveTradeReportQuatation,
  getSaveTradeReportOperatingParameter
])
